package com.zdw.demo.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zdw.common.constant.common.CommonConstants;
import com.zdw.demo.config.zentao.ZenTaoConfig;
import com.zdw.demo.entity.ZentaoUser;
import com.zdw.demo.mapper.ZentaoUserMapper;
import com.zdw.demo.service.ZentaoUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;

@Service
@Slf4j
public class ZentaoUserServiceImpl extends ServiceImpl<ZentaoUserMapper, ZentaoUser> implements ZentaoUserService {

    @Autowired
    private ZentaoUserMapper mapper;

    @Autowired
    private ZenTaoConfig zenTaoConfig;

    /**
     * 根据时间戳、应用代号、账号名生成禅道免登录的TOKEN
     *
     * @param code
     * @param key
     * @param time
     * @return
     */
    public String generateMd5Token(String code, String key, long time) {
        // 将时间戳、code和account拼接起来
        String dataToHash = StrUtil.join(StrUtil.EMPTY, code, key, time);

        // 使用Hutool的SecureUtil生成MD5哈希值
        return SecureUtil.md5(dataToHash);
    }

    /**
     * admin登录,并获取admin的token
     *
     * @return
     */
    public String getAdminToken() {
        // 初始化token
        String adminToken = StrUtil.EMPTY;
        // 创建 HttpClient 实例
        HttpClient httpClient = HttpClient.newHttpClient();
        // 构建请求体
        String requestBody = "{\"account\": \"" + zenTaoConfig.getAdminName() + "\", \"password\": \"" + zenTaoConfig.getAdminPassword() + "\"}";
        // 创建 HttpRequest
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(zenTaoConfig.getLoginUrl() + "/api.php/v1/tokens"))
                .header("Content-Type", "application/json") // 设置 Content-Type 为 application/json
                .POST(HttpRequest.BodyPublishers.ofString(requestBody, StandardCharsets.UTF_8)) // 设置 POST 请求体
                .build();
        // 发送请求并处理响应
        try {
            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
            // 解析 JSON 响应并提取 token
            adminToken = JSONUtil.parseObj(response.body()).getStr("token");
            log.info("Admin Token: " + adminToken);
        } catch (Exception e) {
            log.error("Error occurred while getting admin token: " + e.getMessage());
        }
        return adminToken;
    }

    /**
     * 检查用户是否存在
     *
     * @param account
     * @return
     */
    public boolean checkUserExist(String account) {
        LambdaQueryWrapper<ZentaoUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZentaoUser::getAccount, account);
        ZentaoUser zentaoUser = mapper.selectOne(queryWrapper);
        return ObjectUtil.isNull(zentaoUser);
    }

    /**
     * 初始化禅道账号
     *
     * @param account
     * @return
     */
    public String initZentaoAccount(String account, String realName, String adminToken) {
        // 创建 HttpClient 实例
        HttpClient httpClient = HttpClient.newHttpClient();
        // 构建请求体
        String initPassword = account + zenTaoConfig.getInitPassword();
        realName = StrUtil.isBlank(realName) ? account : realName;
        String requestBody = """
                 {
                   "account": "%s",
                   "password": "%s",
                   "realname":"%s",
                   "gender":"m"
                 }
                """.formatted(account, initPassword, realName);
        // 创建 HttpRequest
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(zenTaoConfig.getLoginUrl() + "/api.php/v1/users"))
                .header("Content-Type", "application/json") // 设置 Content-Type 为 application/json
                .header("Token", adminToken)
                .POST(HttpRequest.BodyPublishers.ofString(requestBody, StandardCharsets.UTF_8)) // 设置 POST 请求体
                .build();
        // 发送请求并处理响应
        try {
            HttpResponse<String> response     = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
            String               responseBody = response.body();
            log.info("create account: " + responseBody);
            // 判断失败
            if (response.statusCode() >= HttpStatus.HTTP_BAD_REQUEST) {
                return CommonConstants.INIT_ZENTAO_ACCOUNT_ERROR;
            }
        } catch (Exception e) {
            log.error("Error occurred while creating account: " + e.getMessage());
        }
        return StrUtil.EMPTY;
    }

}
